﻿using Publicuse.Entity;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Publicuse.Util
{
    /// <summary>
    /// 查询缓存
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class QueryCacheUtil<T> where T : class
    {
        public static ConcurrentDictionary<string, QueryCache<T>> list = null;

        static QueryCacheUtil()
        {
            list = new ConcurrentDictionary<string, QueryCache<T>>();
        }

        /// <summary>
        /// 默认30分钟超时过期
        /// </summary>
        /// <param name="key"></param>
        /// <param name="data"></param>
        /// <param name="day"></param>
        public static void AddData(string key, QueryCache<T> data, int day = 1)
        {
            if (list.ContainsKey(key))
            {
                list.Clear();
                data.ctime = DateTime.Now.AddDays(day);
                list.TryAdd(key, data);
            }
            else
            {
                data.ctime = DateTime.Now.AddDays(day);
                list.TryAdd(key, data);
            }
        }

        public static bool IsExists(string key)
        {
            QueryCache<T> data = null;
            list.TryGetValue(key, out data);
            if (data != null)
            {
                var ctime = data.ctime;
                if (DateTime.Now < ctime)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        public static QueryCache<T> GetData(string key)
        {
            QueryCache<T> data = null;
            list.TryGetValue(key, out data);
            return data;
        }

        public static void RemoveData(string key)
        {
            QueryCache<T> data = null;
            if (list.ContainsKey(key))
            {
                list.TryRemove(key, out data);
            }
        }
    }
}
